package com.hok.misc.file.transmission;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Calendar;
import java.util.Date;

import org.apache.commons.io.FileUtils;

public class MyServer {
	 /** 
     * @param args 
     * @throws IOException  
     */  
    public static void main(String[] args) {  
        MyServer manager = new MyServer();  
        manager.doListen();  
    }  
  
    public void doListen() {  
        ServerSocket server;  
        try {  
            server = new ServerSocket(9991);  
            while (true) {  
            	System.out.println("server running......" + new Date());
                Socket client = server.accept();  
                System.out.println("start accept......" + new Date());
                new Thread(new SSocket(client)).start();  
                System.out.println("end accept......" + new Date());
            }  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
  
    }  
  
    //服务器进程  
    class SSocket implements Runnable {  
    	int i = 0;
        Socket socket;  
        private final StringBuffer FILE_PATH = new StringBuffer("d:/");  
        static final int BUFFER = 2048;  
          
        public SSocket(Socket client) {  
            this.socket = client;  
        }  
  
        public void run() {  
            Calendar today = Calendar.getInstance();  
            File file = new File(FILE_PATH.append(today.get(Calendar.YEAR)+"-"+today.get(Calendar.MONTH)+"-"+today.get(Calendar.DAY_OF_MONTH)).toString());  
            if(!file.exists()){  
                file.mkdir();  
            }  
            DataOutputStream serverToClientTextStream = null;   
              
			try {
				serverToClientTextStream = new DataOutputStream(socket.getOutputStream());
				serverToClientTextStream.writeUTF(" Server received done! " + new Date());
				InputStream is = socket.getInputStream();
				System.out.println("index:" + (i++));
				long start = System.currentTimeMillis();
				FileUtils.copyInputStreamToFile(is, new File(file.getPath() + "/" + new Date().getTime()));
				System.out.println("copy end .... " + ((System.currentTimeMillis() - start)/1000));
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				if (socket != null) {
					try {
						socket.close();
						System.out.println("server close:" + new Date());
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
        }  
    }  
}
